import LoadingPage from '@/components/loading-page';
import CardOrder from './components/card-order';
import request from '@/utils/request';
import { useSelector } from 'react-redux';
import { useCallback, useEffect, useState } from 'react';
import { Button, Dialog, Empty, NavBar, Tabs } from '@nutui/nutui-react-taro';
import Taro, { useDidShow } from '@tarojs/taro';
import { View } from '@tarojs/components';
import { IUser } from '@/types/user';
import { waitForRender } from '@/utils/render';
import { domain2 } from '@/constant';
import { fetchUser, getUser } from '@/utils/user';
import {
  EnumOrderStatus,
  EnumOrderTotalStatus,
  IOrder,
  IOrderTotal,
} from '@/types/order';
import './index.less';

const filterUnPaid = (orderTotalList: IOrder[]) => {
  return orderTotalList.filter(
    (orderTotal) => orderTotal.status === EnumOrderStatus.UNPAID
  );
};

// const filterRefund = (orderTotalList: IOrderTotal[]) => {
//   return orderTotalList.filter((orderTotal) =>
//     [EnumOrderTotalStatus.REFUNDING, EnumOrderTotalStatus.REFUNDED].includes(
//       orderTotal._status
//     )
//   );
// };

const entryRender = (list: any[]) => {
  if (list.length) return list;
  return (
    <View className="empty-box">
      <Empty
        image={<img src={`${domain2}/subtract.png`} alt="" />}
        title="暂无订单"
        description="业主们正在赶来～">
        {/* <Button
          type="primary"
          className="empty-box-button"
          onClick={() =>
            Taro.navigateTo({ url: '/pages/ticket-notice/index' })
          }>
          去购买
        </Button> */}
      </Empty>
    </View>
  );
};

export default function Index() {
  const barHeight = useSelector((state: any) => state.system.barHeight);
  const [user, setUser] = useState(getUser());
  const [tabvalue, setTabvalue] = useState<string | number>('0');
  const [loading, setLoading] = useState<boolean>(true);
  const [orderTotals, setOrderTotals] = useState<IOrder[]>([]);
  const [orderTodayTotals, setOrderTodayTotals] = useState<IOrder[]>([]);
  const [orderTotalsFinished, setOrderTotalsFinished] = useState<IOrder[]>([]);
  const [selectedTag, setSelectedTag] = useState<string>('trash');

  // 刷新所有标签页的数据
  const refreshAllData = useCallback(async (newUser?: IUser) => {
    setLoading(true);
    const userId = user?.id || newUser?.id;
    try {
      const [todayData, allData, finishedData] = await Promise.all([
        request.get<IOrder[]>('/order/list-gly-today', {
          id: userId,
          orderType: selectedTag
        }),
        request.get<IOrder[]>('/order/list-gly', {
          id: userId,
          orderType: selectedTag
        }),
        request.get<IOrder[]>('/order/list-gly-finish-time', {
          id: userId,
          orderType: selectedTag
        })
      ]);
      
      setOrderTodayTotals(todayData);
      setOrderTotals(allData);
      setOrderTotalsFinished(finishedData);
    } catch (error) {
      console.error('加载数据失败', error);
    } finally {
      waitForRender(() => setLoading(false));
    }
  }, [user, selectedTag]);

  const requestForOrders = useCallback(
    async (newUser?: IUser) => {
      setLoading(true);
      const orderTotals = await request
        .get<IOrder[]>('/order/list-gly', {
          id: user?.id || newUser?.id,
          orderType: selectedTag
        })
        .finally(() => {
          waitForRender(() => setLoading(false));
        });
        setOrderTotals(orderTotals);
        return orderTotals;
    },
    [user, selectedTag]
  );

  const requestForOrdersToday = useCallback(
    async (newUser?: IUser) => {
      setLoading(true);
      const orderTotals = await request
        .get<IOrder[]>('/order/list-gly-today', {
          id: user?.id || newUser?.id,
          orderType: selectedTag
        })
        .finally(() => {
          waitForRender(() => setLoading(false));
        });
        setOrderTodayTotals(orderTotals);
        return orderTotals;
    },
    [user, selectedTag]
  );
  
  const requestForOrdersFinished = useCallback(
    async (newUser?: IUser) => {
      setLoading(true);
      const orderTotals = await request
        .get<IOrder[]>('/order/list-gly-finish-time', {
          id: user?.id || newUser?.id,
          orderType: selectedTag
        })
        .finally(() => {
          waitForRender(() => setLoading(false));
        });
        setOrderTotalsFinished(orderTotals);
        return orderTotals;
    },
    [user, selectedTag]
  );

  // 根据当前选中的标签页，刷新对应的数据
  const refreshCurrentTabData = useCallback(async (newUser?: IUser) => {
    if (tabvalue === '0') {
      await requestForOrdersToday(newUser);
    } else if (tabvalue === '1') {
      await requestForOrders(newUser);
    } else if (tabvalue === '2') {
      await requestForOrdersFinished(newUser);
    }
  }, [tabvalue, requestForOrdersToday, requestForOrders, requestForOrdersFinished]);

  useDidShow(() => {
    const _user = getUser();
    if (_user?.id) {
      fetchUser(_user.id).then((res) => setUser(res));
      // 加载所有三个标签页的数据
      refreshAllData(_user);
    } else {
      setLoading(false);
    }
  });

  // 初始加载数据
  useEffect(() => {
    if (!user?.id) {
      setLoading(false);
      return;
    }
    // 加载所有三个标签页的数据
    refreshAllData();
  }, [refreshAllData]);

  // 标签切换时请求新数据
  useEffect(() => {
    if (user?.id) {
      refreshAllData();
    }
  }, [selectedTag, refreshAllData]);

  // 当标签页切换时请求新数据
  useEffect(() => {
    if (user?.id) {
      refreshCurrentTabData();
    }
  }, [tabvalue, refreshCurrentTabData]);

  // 标签页切换时更新状态
  const handleTabChange = (value: string | number) => {
    setTabvalue(value);
  };

  // 处理二级标签切换
  const handleTagChange = (tag: string) => {
    setSelectedTag(tag);
  };

  // 根据当前标签页刷新所需数据
  const refreshCurrentList = useCallback(async () => {
    try {
      setLoading(true);
      
      // 批量刷新所有标签页数据，确保各个列表都是最新的
      const [todayData, allData, finishedData] = await Promise.all([
        request.get<IOrder[]>('/order/list-gly-today', {
          id: user?.id,
          orderType: selectedTag
        }),
        request.get<IOrder[]>('/order/list-gly', {
          id: user?.id,
          orderType: selectedTag
        }),
        request.get<IOrder[]>('/order/list-gly-finish-time', {
          id: user?.id,
          orderType: selectedTag
        })
      ]);
      
      // 更新所有数据
      setOrderTodayTotals(todayData);
      setOrderTotals(allData);
      setOrderTotalsFinished(finishedData);
      
      setLoading(false);
      return true;
    } catch (error) {
      console.error('刷新数据失败', error);
      setLoading(false);
      return false;
    }
  }, [user, selectedTag, setLoading, setOrderTodayTotals, setOrderTotals, setOrderTotalsFinished]);

  return (
    <View className="order">
      <LoadingPage loading={loading} />
      <Dialog id="cancel" />
      <View className="nav-bar">
        <View style={{ height: `${barHeight}px`, width: '100%' }}></View>
        <NavBar>我的订单</NavBar>
      </View>
      <Tabs
        value={tabvalue}
        onChange={handleTabChange}>
        <Tabs.TabPane title="今日待完成">
          <View className="tag-filter">
            <View 
              className={`tag-item ${selectedTag === 'trash' ? 'active' : ''}`}
              onClick={() => handleTagChange('trash')}
            >
              扔垃圾
            </View>
            <View 
              className={`tag-item ${selectedTag === 'parcel' ? 'active' : ''}`}
              onClick={() => handleTagChange('parcel')}
            >
              取快递
            </View>
            <View 
              className={`tag-item ${selectedTag === 'other' ? 'active' : ''}`}
              onClick={() => handleTagChange('other')}
            >
              其他
            </View>
          </View>
          {entryRender(
            orderTodayTotals.map((orderTotal) => (
              <CardOrder
                key={orderTotal.id}
                orderTotal={orderTotal}
                refreshList={refreshCurrentList}
              />
            ))
          )}
        </Tabs.TabPane>
        <Tabs.TabPane title="待完成">
          <View className="tag-filter">
            <View 
              className={`tag-item ${selectedTag === 'trash' ? 'active' : ''}`}
              onClick={() => handleTagChange('trash')}
            >
              扔垃圾
            </View>
            <View 
              className={`tag-item ${selectedTag === 'parcel' ? 'active' : ''}`}
              onClick={() => handleTagChange('parcel')}
            >
              取快递
            </View>
            <View 
              className={`tag-item ${selectedTag === 'other' ? 'active' : ''}`}
              onClick={() => handleTagChange('other')}
            >
              其他
            </View>
          </View>
          {entryRender(
            orderTotals.map((orderTotal) => (
              <CardOrder
                key={orderTotal.id}
                orderTotal={orderTotal}
                refreshList={refreshCurrentList}
              />
            ))
          )}
        </Tabs.TabPane>
        <Tabs.TabPane title="全部订单">
          <View className="tag-filter">
            <View 
              className={`tag-item ${selectedTag === 'trash' ? 'active' : ''}`}
              onClick={() => handleTagChange('trash')}
            >
              扔垃圾
            </View>
            <View 
              className={`tag-item ${selectedTag === 'parcel' ? 'active' : ''}`}
              onClick={() => handleTagChange('parcel')}
            >
              取快递
            </View>
            <View 
              className={`tag-item ${selectedTag === 'other' ? 'active' : ''}`}
              onClick={() => handleTagChange('other')}
            >
              其他
            </View>
          </View>
          {entryRender(
            orderTotalsFinished.map((orderTotal) => (
              <CardOrder
                key={orderTotal.id}
                orderTotal={orderTotal}
                refreshList={refreshCurrentList}
              />
            ))
          )}
        </Tabs.TabPane>
        {/* <Tabs.TabPane title="退款">
          {entryRender(
            filterRefund(orderTotals).map((orderTotal) => (
              <CardOrder
                key={orderTotal.id}
                orderTotal={orderTotal}
                refreshList={requestForOrders}
              />
            ))
          )}
        </Tabs.TabPane> */}
      </Tabs>
    </View>
  );
}
